package me.yiyou.meihua.ui.page.study

import android.content.Context
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.kongzue.dialogx.dialogs.PopTip
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.yiyou.meihua.MyApplication
import me.yiyou.meihua.R
import me.yiyou.meihua.data.Gua
import me.yiyou.meihua.data.GuaList
import java.io.IOException
import kotlin.random.Random

class StudyViewModel : ViewModel() {
    // 状态管理
    val guaList = mutableStateOf<List<Gua>?>(null)
    val isLoading = mutableStateOf(false)
    val error = mutableStateOf<String?>(null)

    // 题目下标
    val currentIndex = mutableStateOf(0)

    // 输入内容的状态管理
    private val _inputContent = mutableStateOf("")
    val inputContent: State<String> get() = _inputContent

    // 输入内容的状态管理
    private val _showExplain = mutableStateOf(false)
    val showExplain: State<Boolean> get() = _showExplain

    /**
     * 显示提示的状态更改
     */
    fun toggleExplain() {
        _showExplain.value = !_showExplain.value
    }

    /**
     * 输入变化回调
     */
    fun onInputChanged(newText: String) {
        _inputContent.value = newText
        // 这里可以添加业务逻辑（如输入验证、数据过滤等）
    }

    /**
     * 清空输入
     */
    fun clearInput() {
        _inputContent.value = ""
    }


    /**
     * 加载卦象json数据
     */
    fun loadGuaData() {
        // 随机一个下标数
        currentIndex.value = randomCurrent()
        viewModelScope.launch(Dispatchers.IO) {
            isLoading.value = true
            try {
                val data = parseGuaFromAssets(MyApplication.appContext, "gua.json")
                guaList.value = data?.gua ?: emptyList()
            } catch (e: Exception) {
                error.value = when (e) {
                    is IOException -> "文件读取失败"
                    is JsonSyntaxException -> "数据解析错误"
                    else -> "未知错误: ${e.message}"
                }
            } finally {
                isLoading.value = false
            }
        }
    }

    /**
     * 生成一个随机数,用作下标
     */
    fun randomCurrent(): Int {
        return Random.nextInt(64) // 生成 0（包含）到 64（不包含）之间的整数
    }

    /**
     * 读取并解析 JSON 的工具函数
     */
    private fun parseGuaFromAssets(context: Context, fileName: String): GuaList? {
        return try {
            val jsonString = context.assets.open(fileName)
                .bufferedReader()
                .use { it.readText() }

            Gson().fromJson(jsonString, GuaList::class.java)
        } catch (e: IOException) {
            e.printStackTrace()
            null
        } catch (e: JsonSyntaxException) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 根据名字查找卦象
     */
    fun findGuaByName(name: String): Gua? {
        return guaList.value?.firstOrNull { it.ming == name }
    }

    /**
     * 切换到下一个卦象
     */
    fun onNextQuestion() {
        guaList.value?.let { list ->
            currentIndex.value = randomCurrent()
        }
        clearInput()
        _showExplain.value = false
    }

    /**
     * 判断回答是否正确,正确切换下一个
     */
    fun checkAnswer(answer: String) {
        if (answer.isNotEmpty()) {
            if (answer == guaList.value?.get(currentIndex.value)?.ming) {
                PopTip.show(R.drawable.icon_success, "回答正确!")
                onNextQuestion()
                clearInput()
                _showExplain.value = false
            } else {
                PopTip.show(R.drawable.icon_error, "回答错误!")
            }
        } else {
            PopTip.show(R.drawable.icon_warning, "请输入答案!")
        }
    }

    /**
     * 当前题目的文本
     */
    val currentPositionText: String
        get() = guaList.value?.let {
            "${currentIndex.value + 1}/${it.size}"
        } ?: "0/0"
}